<?php
if (!init()) {
  redirect('?action=login');
}

if (empty($_POST['header']) || empty($_POST['legend'])) {
  redirect("?action=msg&header=header.fly.empty.fields&body=body.fly.empty.fields&view=flies");
}

include_once("functions/utils/ImageUtil.php");

$uploaddir = getcwd() . \controller\Config::getPropertyByKey('directory.fly');
$acceptedFormats = array('gif', 'png', 'jpg', 'jpeg');

$timeStamp = getLocalTimeStamp();

$insertFlyResultSet = createFly($_POST['header'], $_POST['legend'], f_Date($timeStamp), f_Time($timeStamp));

$idFly = mysql_query("SELECT id FROM flies WHERE time = '" . f_Time($timeStamp) . "' AND date = '" . f_Date($timeStamp) . "'");
$idFly = mysql_fetch_assoc($idFly);
$idFly = $idFly['id'];

$updateFlyResultSet = null;
$mainImgInsertResultSet = null;
$imgInsertResultSet = null;

if (isset($_FILES['image'])) {

  $uploadfile = '';

  if (in_array(strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION)), $acceptedFormats)) {
    $file = date("dmY") . "_" . date("GHi") . getFormattedTime() . "_main_fly_img" . "." . pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
    $uploadfile = $uploaddir . $file;

    if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {

      $mainImgInsertResultSet = createFlyImage($file, $idFly);
      $imgId = mysql_query("SELECT id FROM flyimages WHERE flyid = '" . $idFly . "'");
      $imgId = mysql_fetch_assoc($imgId);
      $imgId = $imgId['id'];
      \util\ImageUtil::createImagePreview($uploadfile, 300, 'preview/fly_img_topic_preview', 'fly_img');
      \util\ImageUtil::createImagePreview($uploadfile, 500, 'preview/fly_main_img_preview', 'fly_img');

      $updateFlyResultSet = updateFlyMainImage($imgId, $idFly);
    }
  }


  if (isset($_FILES['images'])) {
    $i = 0;
    $uploadfile = '';

    while (isset($_FILES['images']['name'][$i]) && $i < 5) {

      if (in_array(strtolower(pathinfo($_FILES['images']['name'][$i], PATHINFO_EXTENSION)), $acceptedFormats)) {
        $file = date("dmY") . "_" . date("GHi") . getFormattedTime() . "_fly_img" . "." . pathinfo($_FILES['images']['name'][$i], PATHINFO_EXTENSION);
        $uploadfile = $uploaddir . $file;

        if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $uploadfile)) {
          $imgInsertResultSet = createFlyImage($file, $idFly);
          \util\ImageUtil::createImagePreview($uploadfile, 300, 'preview/fly_img_topic_preview', 'fly_img');
        }
      }
      $i++;
    }

  }
}

$initiatorAction = \controller\ControllerUtil::getEncodedActionFromUrlWithParameters($_SERVER['HTTP_REFERER']);

if ($insertFlyResultSet) {
  redirect("?action=msg&header=header.fly.success&body=body.fly.success&view=" . $initiatorAction);
} else {
  redirect("?action=msg&header=header.fly.failed&body=body.fly.failed&view=" . $initiatorAction);
}
